#include "xqviewfinderwidget.h"
#include "xqviewfinderwidget_p.h"
#include <QPainter>
#include "cameraengine.h"

const int KErrCameraNotSet = -51;

XQViewFinderWidgetPrivate::XQViewFinderWidgetPrivate(XQViewFinderWidget* qq) : q(qq)
{

}

XQViewFinderWidgetPrivate::~XQViewFinderWidgetPrivate()
{
}

bool XQViewFinderWidgetPrivate::start()
{
    if (!iCamera) {
        iError = KErrCameraNotSet;
        return false;
    }
    ////////////////////////////////added by me
    if (iCamera->d->iCameraEngine->State() == CCameraEngine::EEngineIdle)
            {
            // Prepare camera
            TSize captureSize = TSize(480,360);
            TRAPD(iErrorCamera,iCamera->d->iCameraEngine->PrepareL(captureSize));
            if (iErrorCamera != KErrNone)
                {
                   return false;   //Camera prepare error, should add some alert to user
                }

            // Start viewfinder. Viewfinder pictures starts coming into MceoViewFinderFrameReady();
            TSize viewfinderSize(iCamera->d->iViewFinderSize.width(), iCamera->d->iViewFinderSize.height());
            TRAPD(iErrorViewfinder,iCamera->d->iCameraEngine->StartViewFinderL(viewfinderSize));
            if (iErrorViewfinder != KErrNone)
                {
                   return false;   //Camera start viewfinder error
                }

            return true;
            }
    ////////////////////////////////added by me
}

void XQViewFinderWidgetPrivate::stop()
{
    if (!iCamera) {
        iError = KErrCameraNotSet;
        return;
    }
    iCamera->d->iCameraEngine->StopViewFinder();
}

void XQViewFinderWidgetPrivate::ViewFinderFrameReady(const QImage& image)
{
    setImage(image);
}

void XQViewFinderWidgetPrivate::setCamera(XQCamera& cameraObject)
{
    iCamera = &cameraObject;
    iCamera->d->setVFProcessor(this);
}

void XQViewFinderWidgetPrivate::setImage(const QImage& image)
{

    iImage = image;
    q->repaint();
}

void XQViewFinderWidgetPrivate::setViewfinderSize(QSize size)
{
    if (!iCamera) {
        iError = KErrCameraNotSet;
        return;
    }
    iCamera->d->iViewFinderSize = size;
}

void XQViewFinderWidgetPrivate::paintEvent(QPaintEvent * /*event*/)
{
    QPainter painter(q);
    QPoint point(q->pos());
    QPixmap tempPixmap = QPixmap::fromImage(iImage.scaled(q->size(), Qt::KeepAspectRatio));
    painter.drawPixmap(point, tempPixmap);
}

XQViewFinderWidget::Error XQViewFinderWidgetPrivate::error() const
{
    switch (iError) {
    case KErrNone:
        return XQViewFinderWidget::NoError;
    case KErrNoMemory:
        return XQViewFinderWidget::OutOfMemoryError;
    case KErrCameraNotSet:
        return XQViewFinderWidget::CameraNotSetError;
    default:
        return XQViewFinderWidget::UnknownError;
}    
}

// End of file
